package game;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import objects.WorldObject;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

import util.CledaConnector;
import database.MAction;
import database.MAgent;
import database.MSpecialFeature;
import database.MWorldObject;

public class TestDatabase {

  // https://code.google.com/p/foo-org-ve/source/browse/#svn%2Ftrunk%2FHibernate
  public static void main(String[] args) {

    // SE OBTIENE
    Session session = CledaConnector.getInstance().getSession();
    session.beginTransaction();

    // SE USA
    MWorldObject worldObject = new MWorldObject();
    worldObject.setName("foo");
    //worldObject.setObjectId(1);
    
    
    
    MAgent agent = new MAgent();
    agent.setName("agente1");
    agent.setAgentId(3);
    agent.setObjectReference(worldObject);
    session.save(agent);
    
    
    MSpecialFeature feature = new MSpecialFeature();
    feature.setId(20);
    feature.setName("algoFEature");
    feature.setObjectReference(worldObject);
    session.save(feature);
    
    MAction action = new MAction();
    action.setActionId(34);
    action.setName("action w");
    action.setObjectReference(worldObject);
    session.save(action);
    
    worldObject.getAgentList().add(agent);
    worldObject.getSpecialFeatureList().add(feature);
    worldObject.getActionList().add(action);
    
    MWorldObject obj2 = new MWorldObject();
    obj2.setName("objj2");
    worldObject.setObjectReference(obj2);
    
    
    session.save(worldObject);
    session.save(obj2);

    // NO ABRIR UNA SESION DENTRO DE OTRA!!!

    session.getTransaction().commit();
    // SE CIERRA
    session.close();

    // SE BOTA... (Procurar no poner sesiones como atributos de clases, o andar pasando sesiones por funciones, etc

    // ----------------------------------------

    session = CledaConnector.getInstance().getSession();
    session.beginTransaction();

//    Query q = session.createQuery("FROM MWorldObject");

//    Iterator itt = q.iterate();

//    while (itt.hasNext()) {
//      MWorldObject wo = (MWorldObject) itt.next();
//      System.err.println(wo);
//    }
    
    
//  Query q = session.createQuery("FROM MWorldObject");
//
//  Iterator itt = q.iterate();
//
//  while (itt.hasNext()) {
//	  MWorldObject wo = (MWorldObject) itt.next();
//	  wo.setObjectId(100);
//	  for(MAgent ag : wo.getAgentList()){
//		  ag.setName("abcs");
//	  }
//  }
//  
//
//  session.getTransaction().commit();
//  session.close();
    
/*    List<MWorldObject> list = new ArrayList<MWorldObject>();
    list =session.createCriteria(MWorldObject.class).add(Restrictions.eq("objectId", 1)).list();
    list.get(0).setObjectId(4);
    list =session.createCriteria(MWorldObject.class).list();
    for(MWorldObject obj : list){
    	session.delete(obj);
    }
    session.getTransaction().commit();
    session.close();*/
  }

}
